<?php
 /**
 * ERROR CODE 0600-0700
 *
 * */
class Excel {

	private $error;

	public function __construct() {
		if( empty($this->error) ) {
			if( !empty($GLOBALS['error']) ) {
				$this->error = $GLOBALS['error'];
			} else {
				$this->error = new Error();
				$GLOBALS['error'] = &$this->error;
			}
		}
	}
	
	public function generateFromTemplate( $templatePath , $data , $column = array() ) {
		$template = file_get_contents($templatePath);
		if( $template === false ) {
			$this->error->setError(601,"cannot load file : {$templatePath}");
			return false;
		}
		if( !preg_match_all("!<Row.*>(.*)</Row>!Us", $template, $row1 ) ) {
			$this->error->setError(602,"cannot finde Row");
			return false;
		}
		$template = preg_replace( "!<Table.*>!Us", "<Table>", $template );
		$row =& $row1[0];
		$length = count($row);
		for ($i = 0; $i < $length; $i++) {
			if( !preg_match_all("!<Cell.*>(.*)</Cell>!Us", $row[$i], $cell1 ) ) {
				$this->error->setError(603,"cannot finde Cell");
				return false;
			}
			$cell =& $cell1[0];
			$cellLength = count($cell);
			for ($j = 0; $j < $cellLength; $j++) {
				if( preg_match("!COLUMN:START!Us", $cell[$j]) ) {
					$cellIndex = 0;
					if( preg_match("!Index=\"(.*)\"!Us" ,$cell[$j], $index1) ) {
						$cellIndex = (int)$index1[1];
					}
					$template = preg_replace( "!".$cell[$j]."!Us", "{COLUMNS}", $template ,1 );
					$currCellGroup = "";
					$j++;
					$k = 0;
					do {
						if( $cellIndex != 0 && $k == 0 ) {
							if( !preg_match("!<Cell.*Index.*>", $cell[$j]) ) {
								$currCellGroup .= str_replace( "<Cell", "<Cell ss:Index=\"{$cellIndex}\"", $cell[$j] );
							} else {
								$currCellGroup .= $cell[$j];
							}
						} else {
							$currCellGroup .= $cell[$j];
						}
						$currCellGroup .= "\n\r";
						$template = preg_replace( "!".$cell[$j]."!Us", "", $template ,1 );
						$j++;
						$k++;
					} while ( !preg_match("!COLUMN:END!Us", $cell[$j]) );
					$template = preg_replace( "!".$cell[$j]."!Us", "", $template ,1 );
					$this->generateCellColumns($template,$column,$currCellGroup,$k);
				}
			}
		}
		echo $template;
		file_put_contents("sssss.xml", $template );
	}
	private function generateCellColumns(&$template,$columns,$cellGroup,$k) {
		$q = 0;
		$cell = "";
		foreach ( $columns as $column ) {
			$currCellGroup = $cellGroup;
			$currCellGroup = preg_replace('/Index="([\d]+?)"/e', '   "Index=\"" . ("$1" + $k*$q ) . "\""   ', $currCellGroup);
			foreach ($column as $key => $value) {
				$currCellGroup = str_replace( "::".$key."::", $value, $currCellGroup );
				$currCellGroup = str_replace( "{".$key."}", $value, $currCellGroup );
			}
			$cell .= "\n\r".$currCellGroup;
			$q++;
		}
		$template = str_replace("{COLUMNS}",$cell,$template);
	}
}




























